package com.hyjr.RxTask.netty.handler;

import com.hyjr.bean.CheckBean;
import com.hyjr.common.utils.LogUtils;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class SendCheckResultClientHandler extends ChannelInboundHandlerAdapter {
	private CheckBean checkBean;
	private int sendNum = 0;//发送次数

	public SendCheckResultClientHandler(CheckBean checkBean) {
		this.checkBean = checkBean;
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		super.channelInactive(ctx);
		LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelInactive");
	}

	public void channelActive(ChannelHandlerContext ctx) {
		ctx.writeAndFlush(checkBean);
		LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelActive，发送数据：" + checkBean.toString());
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		if (msg instanceof String) {
			LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelRead结果：" + msg);
			//根据返回信息判断对方是否接收成功
			if(!"SUCCESS".equals(msg)) {
				//不成功再次发送
				if(sendNum == 0) {
					LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelRead沉睡5分钟");
					Thread.sleep(5*60*1000);
				} else if(sendNum == 1) {
					LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelRead沉睡30分钟");
					Thread.sleep(30*60*1000);
				} else if(sendNum == 2) {
					LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelRead沉睡12个小时");
					Thread.sleep(12*60*60*1000);
				}
				LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelRead沉睡后，再次发送数据：" + checkBean.toString());
				ctx.writeAndFlush(checkBean);
			} else {
				LogUtils.debug("检测端，客户端SendCheckResultClientHandler，channelRead，调用channelInactive");
				channelInactive(ctx);
			}
		}
	}

	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		cause.printStackTrace();
		LogUtils.debug("检测端，客户端SendCheckResultClientHandler，exceptionCaught", cause);
		ctx.close();
	}

}
